const express = require('express')
const app = express()
const rateLimit = require('express-rate-limit')
const cors = require('cors')
const port = 3000
const limiter = rateLimit({
  windowMs: 1 * 60 * 1000,
  max: 20,
  standardHeaders: true,
  legacyHeaders: false,
})

app.use(limiter)

let books = [
  {
    id: 1,
    bookname: '三国演义',
    author: '罗贯中'
  },
  {
    id: 2,
    bookname: '西游记',
    author: '吴承恩'
  },
  {
    id: 3,
    bookname: '红楼梦',
    author: '曹雪芹'
  },
  {
    id: 4,
    bookname: '水浒传',
    author: '施耐庵'
  },
]

app.use(cors())
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

app.get('/books/:id?', (req, res) => {
  let id = req.params.id || req.query.id
  if (id) {
    id = +id
    if (isNaN(id)) {
      res.status(400).send({ error: '请传入正确的id' })
    } else {
      let book = books.find(item => item.id === id)
      if (book) {
        res.json(book)
      } else {
        res.status(204).json({ message: null })
      }
    }
  } else {
    res.status(200).json(books)
  }

})


app.post('/books', function (req, res) {
  if (!req.body.bookname || !req.body.author) {
    res.status(400).json({ error: '书名或者作者不能为空！' })
  } else {
    let idArr = books.map(item => item.id)
    let id
    if(idArr.length == 0) {
      id = 1
    } else {
      id = Math.max.apply(null, idArr) + 1
    }
    books.push({
      id,
      bookname: req.body.bookname,
      author: req.body.author
    })
    res.send(req.body)
  }
})

app.delete('/books', function (req, res) {
  let id = +req.query.id
  if (isNaN(id)) {
    res.status(400).json({ error: '请传入正确的id' })
  } else {
    let index = books.findIndex(item => item.id === id)
    if (index >= 0) {
      books.splice(index, 1)
      res.status(200).json({ message: '删除成功！' })
    } else {
      res.status(204).json({ message: null })
    }
  }


})


app.get('/article', function (req, res) {
  res.status(200).json({ title: 'js', author: 'zhangsan', authorId: 1, comment: 'sdfsdf' })
})

app.get('/author/:id', function (req, res) {
  let id = +req.params.id
  if (isNaN(id)) {
    res.status(400).send({ error: '请传入正确的id' })
  } else {
    if (id === 1) {
      res.status(200).json({ authorId: 1, author: 'zhangsan', age: 22, birthPlace: 'CQ' })
    } else {
      res.status(500).json({ message: '没找到这个人' })
    }
  }
})

app.get('/address/:city', function (req, res) {
  let city = req.params.city
  if(city === 'CQ') {
    res.status(200).json({
      city: '重庆',
      description: '重庆位于中国内陆西南部、长江上游地区。面积8.24万平方公里，辖38个区县（26区、8县、4自治县）。常住人口3212.4万人、城镇化率70.32％。人口以汉族为主，少数民族主要有土家族、苗族。重庆是一座独具特色的“山城、江城”，地貌以丘陵、山地为主，其中山地占76％；长江横贯全境，流程691公里，与嘉陵江、乌江等河流交汇。旅游资源丰富，有长江三峡、世界文化遗产大足石刻、世界自然遗产武隆喀斯特和南川金佛山等壮丽景观。'
    })
  } else {
    res.status(204)
  }
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))